<?php
class Invite extends CI_Controller {
	
	public function __construct() {
		parent::__construct ();
		$this->load->model('invite_model');
		$this->load->model('blog_model');
		$this->load->model('user_model');
		$this->load->model('notification_model');
	}
	
	public function index(){
		$from = $this->session->userdata('user_id');
		$to = $this->input->post('uid');
		$bid = $this->input->post('bid');
		$user = $this->user_model->get_user($from);
		$blog = $this->blog_model->get_blog($bid);
		if (!$user||!$blog){
			echo json_encode(array('result'=>false,'msg'=>'未知错误!'));
		} elseif($this->blog_model->check_manage($to,$bid)){
			echo json_encode(array('result'=>false,'msg'=>'他已经是编辑了!')); 
		} elseif ($this->invite_model->be_invited($to,$bid)){
			echo json_encode(array('result'=>false,'msg'=>'他已经被邀请了!'));
		} else {
			$iid = $this->invite_model->add($from,$to,$bid);
			$this->notification_model->add(
					$to,
					$user['uname'].'邀请您成为博客'.$blog['bname'].'的编辑',
					null,
					'同意',
					base_url('index.php/invite/agree/'.$iid),
					'拒绝',
					base_url('index.php/invite/cancel/'.$iid)
			);
			echo json_encode(array('result'=>true));
		}
	}
	
	public function agree($iid){
		$invite = $this->invite_model->get($iid);
		$this->blog_model->add_editor($invite['bid'],$invite['to']);
		$this->invite_model->delete($iid);
		echo json_encode(array('result'=>true));
	}
	
	public function acancel($iid){
		$this->invite_model->delete($iid);
		echo json_encode(array('result'=>true));
	}
}

?>